Set the astronomy picture of the day as your desktop in Gnome using Python

This short bit of python grabs the most recent apod image and sets it as your destop background. This will only work in Gnome currently but to generalise you need only change the last few commands (the stuff after "# set image as background").

It should be pretty self explanatory...

#!/usr/bin/env python

import urllib
import sys
import os
from bs4 import BeautifulSoup

# Retrieve webpage and soupify it
urllib.urlretrieve("http://apod.nasa.gov/apod/astropix.html", "tmp")

f = open("tmp", "r")
data = [line for line in f]
soup = BeautifulSoup(''.join(data))
os.remove("tmp")

# Sometimes there are videos. We can't deal with those so ignore...
try:
	src = soup.body.find_all("a")[1].img["src"]
	if not src:
		sys.exit()
except:
	sys.exit()

# Get full location and image name
location = "http://apod.nasa.gov/apod/" + src
file_name = src.split("/")[-1]

# image directory

image_dir = os.path.realpath(__file__).rsplit("/", 1)[0] + "/images/"

# Check if we already have the image, if not, get it
if file_name not in os.listdir(image_dir):
	urllib.urlretrieve(location, image_dir + file_name)

set image as background
image = "file://" + image_dir + file_name

command = "DISPLAY=:0 GSETTINGS_BACKEND=dconf gsettings set org.gnome.desktop.background picture-uri " + image
os.system(command)
command = "DISPLAY=:0 GSETTINGS_BACEND=dconf gsettings set org.gnome.desktop.background picture-options stretched"
os.system(command)
		

Pictures like this!

apod